#-*-coding:utf-8-*-
import os
import time
import codecs
from configparser import ConfigParser
from multiprocessing import Process

local_path = os.path.join(os.getcwd(),'local.txt' )

code_check_time = 10

def set_code_check_time(t=10):
    """
    设置git检测频率，单位秒
    """
    global code_check_time
    code_check_time = t

def auto_manager_main(fun,*args,**kwargs):
    """
    委托进程
    """
    print('主进程PID:',os.getpid())
    global code_check_time
    _code_check_time = code_check_time
    if 1:
        if not os.path.isfile(local_path):
            f = open(local_path,'w+')
            txt = """[local]
need_stop = 0
need_restart = 0"""
            f.write(txt)
            f.close()
    con = ConfigParser()
    con.read_file(codecs.open(local_path,'r+',"utf-8-sig"))
    con.set('local','need_stop','0')
    con.set('local','need_restart','0')
    con.write(open(local_path,'w+'))
    _f = True
    while True:
        con.read_file(codecs.open(local_path,'r+',"utf-8-sig"))
        if not con.get('local','need_stop') == '1':
            _res = os.popen('git pull').read()
            if 'Fast-forward' in _res:
                con.set('local','need_stop','1')
            else:
                con.set('local','need_stop','0')
            con.write(open(local_path,'w+'))
        if con.get('local','need_restart') == '1' or _f:
            _f = False
            p = Process(target=fun,args=args,kwargs=kwargs)
            p.start()
            con.set('local', 'need_restart','0')
            con.write(open(local_path,'w+'))
        time.sleep(10)

def check_stop_flag():
    """
    检测是否应该停止，在被托管的进程里使用
    """
    con = ConfigParser()
    con.read_file(codecs.open(local_path,'r+','utf-8-sig'))
    if con.get('local','need_stop') == "1":
        print('code was updata,now stop running!!')
        con.set('local','need_stop',"0")
        con.set('local','need_restart',"1")
        con.write(open(local_path,"w+"))
        exit(0)
        